<template>
  <!-- 会议时长占比 -->
  <div class="chart-box2">
    <div class="chart-title w-100p">会议时长占比</div>
    <div class="chart-content">
      <div class="chart-container" :id="chartId"></div>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  onBeforeUnmount,
  nextTick,
  watch,
} from "vue";
import { Chart, registerTheme } from "@antv/g2";
import common from "../../utils/common";
import store from "../../../../store";

export default defineComponent({
  name: "MeetingRoomDuration",
  setup() {
    const state = reactive({
      chartId: "meetingRoomDurationChart",
      chart: null,
      data: [],
    });

    const initChart = () => {
      const data = state.data;

      state.chart = new Chart({
        container: state.chartId,
        autoFit: true,
        theme: "chartTheme",
      });

      state.chart.data(data);

      state.chart.coordinate("theta", {
        radius: 0.85,
      });

      state.chart.scale("percent", {
        formatter: (val) => {
          val = val + "%";
          return val;
        },
      });
      state.chart.legend({
        position: "right",
        flipPage: false,
        itemHeight: 6,
      });
      state.chart.axis(false); // 关闭坐标轴
      state.chart
        .interval()
        .adjust("stack")
        .position("percent")
        .color("groupName")
        .label("percent", {
          offset: -20,
          style: {
            textAlign: "center",
            shadowBlur: 2,
            shadowColor: "rgba(0, 0, 0, .45)",
            fill: "#fff",
          },
        })
        .tooltip("groupName*percent", (groupName, percent) => {
          percent = percent + "%";
          return {
            name: groupName,
            value: percent,
          };
        })
        .style({
          lineWidth: 1,
          stroke: "#fff",
        });
      state.chart.interaction("element-single-selected");
      state.chart.render();
    };

    watch(
      () => store.getters.centerControl.MeetingRoom_meetingTimeRatio,
      (val) => {
        if (val) {
          getData();
        }
      }
    );

    const getData = () => {
      const { MeetingRoom_meetingTimeRatio } = store.getters.centerControl;
      if (MeetingRoom_meetingTimeRatio) {
        state.data = MeetingRoom_meetingTimeRatio?.list || [];
        if (state.chart) {
          state.chart.changeData(state.data);
        } else {
          nextTick(() => {
            initChart();
          });
        }
      }
    };

    onMounted(() => {
      registerTheme("chartTheme", common.chartTheme);
      getData();
    });

    onBeforeUnmount(() => {
      const chartBox = document.getElementById(state.chartId);
      if (chartBox) {
        chartBox.innerHTML = "";
      }
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
@import "../../styles/common.less";
</style>
